
package com.beiru.sharePreference;
import android.content.Context;
import android.content.SharedPreferences;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class RNSharePreferenceModule extends ReactContextBaseJavaModule {

  public static final String FILE_NAME = "react-native-sharepreference";

    private final ReactApplicationContext reactContext;

    public RNSharePreferenceModule(ReactApplicationContext reactContext) {
      super(reactContext);
      this.reactContext = reactContext;
    }

    @Override
    public String getName() {
      return "RNSharePreference";
    }

    @ReactMethod
    public void saveValue(String saveKey,String saveValue, Promise promise){
      if(saveKey==null || saveValue==null || saveKey.length()==0 || saveValue.length()==0){
        promise.reject("-1","key或value为空");
        return;
      }
      SharedPreferences.Editor editor = getEditor(this.reactContext);
      editor.putString(saveKey,saveValue);
      editor.commit();
      promise.resolve(true);

    }

    @ReactMethod
    public void getValue(String key, Promise promise){
      if(key==null || key.length()==0){
        promise.reject("-1","key为空");
        return;
      }
      SharedPreferences sp = reactContext.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      String value =  sp.getString(key,null);
      promise.resolve(value);

    }

    @ReactMethod
    public void remove(String key, Promise promise){
      if(key==null || key.length()==0){
        promise.reject("-1","key为空");
        return;
      }
      SharedPreferences.Editor editor = getEditor(this.reactContext);
      editor.remove(key);
      editor.commit();
      promise.resolve(true);
    }

    public static SharedPreferences.Editor getEditor(Context context){
      SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
              Context.MODE_PRIVATE);
      return sp.edit();
    }




}
